// base
import Taro, { Component } from '@tarojs/taro'
import { View, Button, Image, Text } from '@tarojs/components'
// redux
import { connect } from '@tarojs/redux'
import { DOREQUESTONEKEYLOGIN } from './store/actions/pageonekeylogin'
import { UPDATEPAGEONEKEYLOGIN } from './store/types/pageonekeylogin'
import { UPDATEUSERINFO } from '../../../store/types/userinfo'
// less
import './index.less'
// libs
import pageonekeylogin from './store/reducers/pageonekeylogin'
import { getStore } from '../../../store/index'
import { getStorageSync } from '../../../crossplatform/apiservice/storage'
import { injectReducer } from '../../../store/reducerUtils'
import { miniLogo, phoneBg } from '../../../configuration/staticimg'
import { navigateTo, redirectTo } from '../../../crossplatform/apiservice/navigate'
import pagejumplist from '../../../configuration/pagejumplist.json'
import { extractPhoneRequest, bindPhoneRequest } from '../../../service/login-controller'
import { showToast } from '../../../crossplatform/apiservice/toast'

const store = getStore()
injectReducer(store, {
  key: 'pageonekeylogin',
  reducer: pageonekeylogin
})

const mapActiontoProps = dispatch => ({
  updateState(payload) {
    dispatch({
      type: UPDATEPAGEONEKEYLOGIN,
      payload: {
        ...payload
      }
    })
  },
  dorequest() {
    return new Promise(resolve => {
      let promise = DOREQUESTONEKEYLOGIN()
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  },
  updateUserState(payload) {
    dispatch({
      type: UPDATEUSERINFO,
      payload: {
        ...payload
      }
    })
  }
})

@connect(
  ({ pageonekeylogin, userinfo }) => ({
    ...pageonekeylogin,
    openId: userinfo.openId
  }),
  mapActiontoProps
)
class OnekeyLogin extends Component {
  config = {
    navigationBarTitleText: ''
  }

  componentWillMount() {
    // onLoad
    const userinfo = getStorageSync('userinfo')
    this.props.updateUserState({
      ...userinfo
    })
  }

  componentDidMount() {
    // onready
  }

  componentDidShow() {
    // onshow
  }

  componentDidHide() {
    // onhide
  }

  componentWillUnmount() {
    // onUnload
  }

  getPhoneNumber = e => {
    // 获取用户手机号
    const { openId } = this.props
    const { detailIn = '', type } = this.$router.params
    const { encryptedData, iv } = e.detail
    if (openId) {
      extractPhoneRequest({ openId, encryptedData, iv }).then(({ data }) => {
        const { data: dataEntry, code, message } = data
        if (code === 200) {
          const { purePhoneNumber } = dataEntry
          bindPhoneRequest({ openId, mobile: purePhoneNumber }).then(({ data: datain }) => {
            const { data: entry, code, message } = datain
            if (code === 200) {
              const { userId, mobile } = entry
              this.props.updateUserState({
                userId,
                mobile
              })
              redirectTo({
                url: `${pagejumplist['base-information'].path}${
                  detailIn ? `?detailIn=${detailIn}` : ''
                }${
                  type ? `?type=${type}` : ''
                }`
              })
            } else {
              showToast({
                title: message || '绑定失败'
              })
            }
          })
        } else {
          showToast({
            title: message || '绑定失败'
          })
        }
        console.log(data, 'dafdsafasdfasdf')
      })
    }
  }

  goRules = () => {
    // 跳转到人职初协议页面
    navigateTo({
      url: `${pagejumplist['agreement-page'].path}`
    })
  }

  goPhone = () => {
    // 跳转手机验证码
    const { detailIn = '', type } = this.$router.params
    redirectTo({
      url: `${pagejumplist['phone-validation'].path}?login=1${
        detailIn ? `&detailIn=${detailIn}` : ''
      }${
        type ? `&roleType=${type}` : ''
      }`
    })
  }

  render() {
    return (
      <View className="OnekeyLogin_id97826">
        <Image className="bg" src={phoneBg} />

        <View className="logo">
          <Image src={miniLogo} />
        </View>
        <Button
          className="onekey-btn"
          OpenType="getPhoneNumber"
          onGetPhoneNumber={this.getPhoneNumber}
        >
          微信用户一键登录
        </Button>

        <View className="sub-login" onClick={this.goPhone}>
          手机号码登录/注册
        </View>

        <View className="bottom-rule">
          <Text>登录代表您已同意</Text>
          <Text className="rule-right" onClick={this.goRules}>
            《人职初协议》
          </Text>
        </View>
      </View>
    )
  }
}

export default OnekeyLogin
